/*
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  Author: g0tsu
 *  Email:  g0tsu at dnmx.0rg
 */

#include <libcaptcha.h>
#include <global.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

void lc_recalculate_arr(lc_arrGlyph *arr) {
  int xline = 0,
      yline = 0;

  for (int i = 0; i < arr->size; i++) {
    yline = MAX(arr->items[i]->h + arr->items[i]->y, yline);
    xline = arr->items[i]->w + arr->items[i]->x;
  }

  arr->w = xline;
  arr->h = yline;
}

__attribute__((deprecated))
lc_arrGlyph * lc_randomize_arr_rotation(lc_arrGlyph *arr, int delta) {
  char bytes[arr->size];
  int angle;
  lc_arrGlyph * narr;

  if ((narr = malloc(sizeof(*narr))) == NULL) {
    errno = ENOMEM;
    return NULL;
  }

  narr->type = LC_TYPE_ARR;
  narr->size = arr->size;
  narr->w = arr->w;
  narr->h = arr->h;

  if ((narr->items = malloc(sizeof(lc_bmpGlyph) * narr->size)) == NULL) {
    errno = ENOMEM;
    return NULL;
  }

  lc_random_bytes(&bytes, narr->size);

  for (int i = 0; i < arr->size; i++) {
    angle = bytes[i] % delta;

    narr->items[i] = lc_rotate_glyph(arr->items[i], angle);
    narr->items[i]->x = arr->items[i]->x;
    narr->items[i]->y = arr->items[i]->y;

    if (!narr->items[i]) {
      lc_free(narr);
      return NULL;
    }
  }

  lc_recalculate_arr(narr);
  return narr;
}

void lc_randomize_arr_rotation_180(lc_arrGlyph *arr) {
  int arrsiz = arr->size;
  char bytes[arrsiz];
  lc_bmp *bmp;

  lc_random_bytes(&bytes, arrsiz);

  for (int i = 0; i < arrsiz; i++) {
    if (bytes[i] > 100) {
      bmp = lc_rotate_bmp_180(arr->items[i]->buffer, arr->items[i]->w, arr->items[i]->h);
      memcpy(arr->items[i]->buffer, bmp->buffer, (bmp->w * bmp->h) * bmp->ch);
      lc_free(bmp);
    }
  }
}

void lc_randomize_arr_x(lc_arrGlyph *arr, int delta) {
  int arrsiz = arr->size;
  char bytes[arrsiz];
  int xline = 0;

  lc_random_bytes(&bytes, arrsiz);

  for (int i = 0, j = 0 ; i < arrsiz; i++) {
    int r = bytes[j++] % delta;
    arr->items[i]->x += r;

    for (int j = i + 1; j < arrsiz; j++) {
      arr->items[j]->x += r;
    }

    xline = MAX(arr->items[i]->x + arr->items[i]->w, xline);
  }

  arr->w = xline;
}

void lc_randomize_arr_y(lc_arrGlyph *arr, int delta) {
  int arrsiz = arr->size;
  int dhalf = delta / 2;
  char bytes[arrsiz];

  lc_random_bytes(&bytes, arrsiz);

  for (int i = 0, j = 0 ; i < arrsiz; i++) {
    int r = bytes[j++] % delta;
    arr->items[i]->y += r;
  }

  lc_recalculate_arr(arr);
}

